<template>
  <div class="content-detail">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <button class="back-btn" @click="goBack">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
      <h2 class="nav-title">笔记详情</h2>
      <div class="nav-right"></div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <div class="error-icon">⚠️</div>
      <h3>加载失败</h3>
      <p>{{ error }}</p>
      <button @click="goBack" class="back-button">返回</button>
    </div>

    <!-- 内容详情 -->
    <div v-else-if="content" class="content-container">
      <!-- 作者信息 -->
      <div class="author-section">
        <div class="author-avatar">
          <span class="avatar-icon">👤</span>
        </div>
        <div class="author-info">
          <div class="author-name">{{ content.author_nickname }}</div>
          <div class="publish-time">{{ formatTime(content.published_at) }}</div>
        </div>
      </div>

      <!-- 标题 -->
      <h1 class="detail-title">{{ content.title }}</h1>

      <!-- 标签 -->
      <div v-if="content.tag_names && content.tag_names.length > 0" class="tags-section">
        <span v-for="tag in content.tag_names" :key="tag" class="tag">#{{ tag }}</span>
      </div>

      <!-- 描述 -->
      <div v-if="content.description" class="description">{{ content.description }}</div>

      <!-- 媒体内容 -->
      <div class="media-section">
        <div v-for="(media, index) in content.media_list" :key="index" class="media-item">
          <!-- 图片 -->
          <img 
            v-if="media.media_type === 'image'" 
            :src="media.url" 
            :alt="`图片 ${index + 1}`"
            @click="previewImage(media.url)"
            class="media-image"
          />
          
          <!-- 视频 -->
          <video 
            v-else-if="media.media_type === 'video'" 
            :src="media.url" 
            controls
            class="media-video"
            @loadedmetadata="onVideoLoaded($event, media)"
          ></video>
        </div>
      </div>

      <!-- 互动数据 -->
      <div class="stats-section">
        <div class="stat-item">
          <span class="stat-icon">👀</span>
          <span class="stat-value">{{ formatNumber(content.view_count) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">❤️</span>
          <span class="stat-value">{{ formatNumber(content.like_count) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">💬</span>
          <span class="stat-value">{{ formatNumber(content.comment_count) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">📤</span>
          <span class="stat-value">{{ formatNumber(content.share_count) }}</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="actions-section">
        <button class="action-button like-button" @click="handleLike">
          <span class="button-icon">{{ isLiked ? '❤️' : '🤍' }}</span>
          <span class="button-text">{{ isLiked ? '已赞' : '点赞' }}</span>
        </button>
        <button class="action-button comment-button" @click="handleComment">
          <span class="button-icon">💬</span>
          <span class="button-text">评论</span>
        </button>
        <button class="action-button share-button" @click="handleShare">
          <span class="button-icon">📤</span>
          <span class="button-text">分享</span>
        </button>
      </div>
    </div>

    <!-- 图片预览模态框 -->
    <div v-if="showImageViewer" class="image-viewer" @click="closeImageViewer">
      <img :src="previewImageUrl" class="viewer-image" @click.stop />
      <button class="close-button" @click="closeImageViewer">✕</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { contentAPI } from '../api'

const route = useRoute()
const router = useRouter()

// 响应式数据
const content = ref(null)
const loading = ref(false)
const error = ref(null)
const isLiked = ref(false)
const showImageViewer = ref(false)
const previewImageUrl = ref('')

// 获取内容详情
const fetchContentDetail = async () => {
  const contentId = route.params.id
  if (!contentId) {
    error.value = '内容ID不存在'
    return
  }

  try {
    loading.value = true
    error.value = null
    
    const response = await contentAPI.getContentDetail(contentId)
    
    if (response.data.success) {
      content.value = response.data.data
    } else {
      error.value = response.data.message || '加载失败'
    }
  } catch (err) {
    console.error('加载内容详情失败:', err)
    error.value = '加载失败，请稍后重试'
    
    if (err.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      router.push('/login')
    }
  } finally {
    loading.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 点赞
const handleLike = () => {
  isLiked.value = !isLiked.value
  if (isLiked.value) {
    content.value.like_count = (content.value.like_count || 0) + 1
  } else {
    content.value.like_count = Math.max(0, (content.value.like_count || 0) - 1)
  }
}

// 评论
const handleComment = () => {
  // TODO: 实现评论功能
  alert('评论功能开发中')
}

// 分享
const handleShare = () => {
  if (navigator.share) {
    navigator.share({
      title: content.value.title,
      text: content.value.description,
      url: window.location.href
    }).catch(err => {
      console.log('分享失败:', err)
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href).then(() => {
      alert('链接已复制到剪贴板')
    })
  }
}

// 预览图片
const previewImage = (url) => {
  previewImageUrl.value = url
  showImageViewer.value = true
}

// 关闭图片预览
const closeImageViewer = () => {
  showImageViewer.value = false
}

// 视频加载完成
const onVideoLoaded = (event, media) => {
  const video = event.target
  if (!media.duration && video.duration) {
    media.duration = Math.round(video.duration)
  }
}

// 格式化数字
const formatNumber = (num) => {
  if (!num) return '0'
  if (num < 1000) return num.toString()
  if (num < 10000) return (num / 1000).toFixed(1) + 'k'
  if (num < 100000000) return (num / 10000).toFixed(1) + 'w'
  return (num / 100000000).toFixed(1) + '亿'
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  
  const now = new Date()
  const time = new Date(timeStr)
  const diff = now - time
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return Math.floor(diff / minute) + '分钟前'
  } else if (diff < day) {
    return Math.floor(diff / hour) + '小时前'
  } else if (diff < week) {
    return Math.floor(diff / day) + '天前'
  } else if (diff < month) {
    return Math.floor(diff / week) + '周前'
  } else {
    return time.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  }
}

// 组件挂载时加载数据
onMounted(() => {
  fetchContentDetail()
})
</script>

<style scoped>
.content-detail {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 20px;
}

.top-nav {
  position: sticky;
  top: 0;
  left: 0;
  width: 100%;
  height: 56px;
  background: #fff;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.back-btn {
  background: transparent;
  border: none;
  padding: 8px;
  cursor: pointer;
  color: #333;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.nav-right {
  width: 40px;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #ff2442;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.error-container h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.error-container p {
  color: #999;
  margin-bottom: 16px;
}

.back-button {
  background: #ff2442;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
}

.content-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.author-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.author-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-icon {
  font-size: 24px;
}

.author-info {
  flex: 1;
}

.author-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.publish-time {
  font-size: 13px;
  color: #999;
}

.detail-title {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin: 0 0 16px 0;
  line-height: 1.4;
}

.tags-section {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.tag {
  background: #f0f0f0;
  color: #ff2442;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 13px;
  font-weight: 500;
}

.description {
  font-size: 16px;
  color: #666;
  line-height: 1.8;
  margin-bottom: 24px;
  white-space: pre-wrap;
  word-break: break-word;
}

.media-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

.media-item {
  width: 100%;
}

.media-image {
  width: 100%;
  border-radius: 12px;
  cursor: pointer;
}

.media-video {
  width: 100%;
  border-radius: 12px;
  background: #000;
}

.stats-section {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
  margin-bottom: 20px;
  background: #fff;
  border-radius: 12px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-icon {
  font-size: 24px;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.actions-section {
  display: flex;
  gap: 12px;
  margin-top: 24px;
}

.action-button {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px;
  background: #fff;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-button:hover {
  background: #fff5f6;
  border-color: #ff2442;
  transform: translateY(-2px);
}

.action-button.liked {
  background: #fff5f6;
  border-color: #ff2442;
}

.button-icon {
  font-size: 24px;
}

.button-text {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

.action-button.liked .button-text {
  color: #ff2442;
}

/* 图片预览模态框 */
.image-viewer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.95);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.viewer-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.close-button {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

